using System;
using System.Collections.Generic;
using UnityEngine;

public class FMSLite
{
    /// <summary>
    /// 当前状态
    /// </summary>
    private string mCurrentState;
    public string State => mCurrentState;
    
    /// <summary>
    /// 转移回调委托
    /// </summary>
    /// <param name="param"></param>
    public delegate void FMSCallback(params object[] param);
    
    /// <summary>
    /// 转移
    /// </summary>
    private class  FMSTranslation
    {
        public string TriggerName;
        public string FromState;
        public string ToState;
        public FMSCallback FmsCallbackAction;

        public FMSTranslation(string triggerName, string fromState, string toState, FMSCallback fmsCallbackAction)
        {
            TriggerName = triggerName;
            FromState = fromState;
            ToState = toState;
            FmsCallbackAction = fmsCallbackAction;
        }
    }

    /// <summary>
    /// 状态
    /// </summary>
    private class FMSState
    {
        public string Name;
        public Dictionary<string, FMSTranslation> TranslationDic = new Dictionary<string, FMSTranslation>();

        public FMSState(string name)
        {
            this.Name = name;
        }
    };
    /// <summary>
    /// 状态字典
    /// </summary>
    private readonly Dictionary<string, FMSState> mStateDic = new Dictionary<string, FMSState>();

    /// <summary>
    /// 添加状态
    /// </summary>
    /// <param name="name"></param>
    public void AddState(string name)
    {
        mStateDic[name] = new FMSState(name);
    }

    /// <summary>
    /// 添加转移状态
    /// </summary>
    /// <param name="trigger">触发器名字</param>
    /// <param name="fromState">起始状态名字</param>
    /// <param name="toState">目标状态名字</param>
    /// <param name="action">转移回调函数</param>
    public void AddTranslation(string trigger, string fromState, string toState, FMSCallback action)
    {
        mStateDic[fromState].TranslationDic[trigger] = new FMSTranslation(trigger,fromState,toState,action);
    }

    /// <summary>
    /// 触发器触发
    /// </summary>
    /// <param name="trigger">触发器名字</param>
    /// <param name="param">回调的参数</param>
    public void Trigger(string trigger, params object[] param)
    {
        
        Debug.Log("显示：" + State + "触发：" + trigger);
        if (mStateDic[State].TranslationDic.ContainsKey(trigger))
        {
            var translation = mStateDic[State].TranslationDic[trigger];
            translation.FmsCallbackAction?.Invoke(param);
            mCurrentState = translation.ToState;
        }
    }

    /// <summary>
    /// 状态机设置开始状态
    /// </summary>
    /// <param name="name"></param>
    public void Start(string name)
    {
        mCurrentState = name;
    }

    public void Clear()
    {
        mStateDic.Clear();
    }
}
